package com.example.deploysinggle.test1.common.filter;

import com.example.deploysinggle.test1.common.context.QiuContext;
import com.example.deploysinggle.test1.common.redis.CacheService;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/12/15 19:17
 */
@Component
public class IPFilter implements Filter {

    @Setter(onMethod_ = @Autowired)
    private CacheService cacheService;

    @Value("${api.judge.ip.expireTime}")//600000      ip：  60000
    private Long ipExpireTime;
    //存入redis前缀
    private static final String IP_FILTER_KEY        = "ip_filter_";

    private static final String X_FORWARD_FOR        = "X-Forwarded-For";

    private static final String X_REAL_IP             = "X-Real-IP";

    private static final String PROXY_CLIENT_IP       = "Proxy-Client-IP";

    private static final String WL_PROXY_CLIENT_IP     = "WL-Proxy-Client-IP";

    private static final String HTTP_CLIENT_IP          = "HTTP-Client-IP";

    private static final String HTTP_X_FORWARDED_FOR   = "HTTP_X_FORWARDED_FOR";

    private static final String COMMA = "," ;

//定义可能的请求头名称
    private static final String[] HEADER_NAMES = {
        X_FORWARD_FOR,
        X_REAL_IP,
        PROXY_CLIENT_IP,
        WL_PROXY_CLIENT_IP,
        HTTP_CLIENT_IP,
        HTTP_X_FORWARDED_FOR

};


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          String clientIp = "";
        if(request instanceof HttpServletRequest){
            HttpServletRequest getClientIp = (HttpServletRequest) request;
              clientIp = getClientIp(getClientIp);
            QiuContext.setOriIp(clientIp);
        }
        try {
            chain.doFilter(request, response);
        } finally {
            QiuContext.removeOriIp();
            //修改redis 访问次数
            modifyRedisTimes(clientIp);
        }
    }

    private void modifyRedisTimes(String clientIp) {
        String redisKey = IP_FILTER_KEY + clientIp;
        //存入redis 如果从redis查到空 null  设置为1  否则  自增1

        if(cacheService.get(redisKey) == null){
            cacheService.set(redisKey, 1, ipExpireTime) ;
        }
        else
        {
            cacheService.increment(redisKey, 1L);
        }

    }

    private  String getClientIp(HttpServletRequest request){
        for (String headerName : HEADER_NAMES) {
             String headerValue = request.getHeader(headerName);
             if(StringUtils.isBlank(headerValue)){
                 continue;
             }
             headerValue =headerValue.trim();
             int commaIndex = StringUtils.indexOf(headerValue, COMMA);
             return commaIndex >= 0 ? StringUtils.substring(headerValue, commaIndex + 1) :headerValue;
        }
        //如果请求头没有  直接返回直接连接的ip地址
        return request.getRemoteAddr();
    }
}
